// TrackingSubBgr.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\imgproc\imgproc.hpp"
#include "iostream"

using namespace cv;
using namespace std;

const char * PATH = "E:\\Test\\SAM_3189.AVI";

void readAVI(std::string path){
	VideoCapture video(path);

	while (true)
	{
		try{
			Mat frame;		
			video.read(frame);
			imshow("VIDEO",frame);
		}catch(cv::Exception ex){
			cout<<"co loi: "<<ex.err;
		}
		if(waitKey(30) == 27) break;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
/*	Mat frameSum, frameTB,frameSS;
	//cong don cac frame lai ~ 250 frame
	VideoCapture video(PATH);
	int countFrameBack=0;
	if(video.read(frameSum)){
		countFrameBack=1;
	}

	while (true)
	{
		try{
			Mat frame;		
			if(video.read(frame)){
			//imshow("VIDEO",frame);
			frameSum = frameSum + frame;
			countFrameBack++;
		//	cout<<countFrameBack<<endl;
			}
		}catch(cv::Exception ex){
			cout<<"co loi: "<<ex.err;
		}
		waitKey(30);
	}

	//frameTB = frameSum/countFrameBack;
	//cout<<"Frame tong: "<<countFrameBack;
	//imshow("anh trung binh",frameTB);

	/*
	xac dinh phan sai khac giua 2 anh

	*/
	Mat frame_1, frame_500;

	VideoCapture video(PATH);
	int countFrameBack=0;

	while (countFrameBack<3)
	{
		Mat frame;	
		try{	
			if(video.read(frame)){
				if(countFrameBack==1){
					frame_1 = frame;
					//cv::imshow("anh 1",frame_1);
				}
				countFrameBack++;
			}
		}catch(cv::Exception ex){
			cout<<"co loi: "<<ex.err;
		}
		waitKey(30);
	}
	cout<<"xong 1"<<endl;

	VideoCapture video1(PATH);
	countFrameBack=0;
	Scalar lowerBound = Scalar(10, 10, 10);
	Scalar upperBound = Scalar(254, 254, 254);
	while (true)
	{
		Mat frame;	
		try{	
			if(video1.read(frame)){
				/*if(countFrameBack == 750)
				{
					frame_500 = frame;
					cout<<countFrameBack;
				}*/
				Mat sub = abs(frame - frame_1);
				Mat kq;
				cv::inRange(sub, lowerBound, upperBound, kq);
				cv::imshow("VIDEO",kq);
			}
		}catch(cv::Exception ex){
			cout<<"co loi: "<<ex.err;
		}
		waitKey(30);
	}

	//xay dung sai so chuan
/*	Mat frameDon, frameTemp;
	VideoCapture video(PATH);
	int countFrameBack=0;
	Mat tempf;
	if(video.read(tempf)){
		countFrameBack++;
		pow(abs(tempf-frameTB),2, frameTemp);
		frameDon += frameTemp;
	}

	while (countFrameBack<200)
	{
		try{
			Mat frame;		
			video.read(frame);
			imshow("VIDEO",frame);
			
			pow(abs(frame-frameTB),2, frameTemp);
			frameDon += frameTemp;
			countFrameBack++;
		}catch(cv::Exception ex){
			cout<<"co loi: "<<ex.err;
		}
		waitKey(30);
	}


	/*
		*
		*phat hien doi tuong chuyen dong
		*
	*/



	cvWaitKey(0);
	return 0;
}

